<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Cache;

class Category extends Model
{
    use SoftDeletes;

    protected $guarded = [];

    protected $dates = ['deleted_at'];

    public function books()
    {
        return $this->belongsToMany(Book::class, 'book_category_relations','category_id','book_id');
    }

    public function getParentCategories()
    {
        return Cache::remember('book-shop:category:parent-categories', 24*60, function(){
            return $this->calculateParentCategories();
        });
    }

    private function calculateParentCategories()
    {
        $categories_arr = [];
        $categories = $this->newQuery()->where('pid',0)->orderBy('sort','asc')->get();
        if(!empty($categories))
        {
            foreach ($categories as $v)
            {
                $categories_arr[] = [
                    'id'    => $v->id,
                    'title' => $v->title,
                    'icon'  => $v->icon,
                    'sort'  => $v->sort,
                ];
            }
        }

        return $categories_arr;
    }
}
